<template>
  <div class="mbti-test" v-loading="loading">
    <div v-if="questions.length > 0" class="test-container">
      <!-- 进度条 -->
      <el-progress
        :percentage="progressPercentage"
        :format="format => `${currentIndex + 1}/${totalQuestions}`"
        class="progress-bar"
      ></el-progress>

      <!-- 当前问题 -->
      <div class="question-container" v-if="currentQuestion">
        <h3 class="question-title">{{ currentQuestion.content }}</h3>
        <div class="options">
          <el-radio-group v-model="currentAnswer" class="option-group">
            <el-radio
              v-for="option in currentQuestion.options"
              :key="option.value"
              :label="option.value"
              class="option-item"
            >
              {{ option.label }}
            </el-radio>
          </el-radio-group>
        </div>
      </div>

      <!-- 导航按钮 -->
      <div class="navigation-buttons">
        <el-button
          :disabled="currentIndex === 0"
          @click="prevQuestion"
          icon="el-icon-arrow-left"
        >
          上一题
        </el-button>
        <el-button
          type="primary"
          :disabled="!currentAnswer"
          @click="nextQuestion"
          :icon="isLastQuestion ? '' : 'el-icon-arrow-right'"
          :loading="loading"
        >
          {{ isLastQuestion ? '提交' : '下一题' }}
        </el-button>
      </div>
    </div>
    <div v-else-if="!loading" class="no-questions">
      <el-empty description="暂无测试题目"></el-empty>
    </div>
  </div>
</template>

<script>
import { testApi, mbtiTypeApi } from '@/api'

export default {
  name: 'MbtiTest',
  data() {
    return {
      questions: [],
      currentIndex: 0,
      answers: {},
      loading: false,
      dimensions: ['EI', 'SN', 'TF', 'JP'],
      scores: {
        E: 0, I: 0,
        S: 0, N: 0,
        T: 0, F: 0,
        J: 0, P: 0
      },
      saveTimer: null, // 用于防抖保存
      testSubmitted: false // 标记测试是否已提交
    }
  },
  computed: {
    totalQuestions() {
      return this.questions.length
    },
    currentQuestion() {
      return this.questions[this.currentIndex]
    },
    currentAnswer: {
      get() {
        const value = this.answers[this.currentQuestion?.id] || ''
        console.log('获取当前答案：', {
          questionId: this.currentQuestion?.id,
          value: value
        })
        return value
      },
      set(value) {
        if (this.currentQuestion) {
          console.log('设置当前答案：', {
            questionId: this.currentQuestion.id,
            oldValue: this.answers[this.currentQuestion.id],
            newValue: value
          })
          
          // 如果值没有变化，不执行任何操作
          if (this.answers[this.currentQuestion.id] === value) {
            console.log('答案未实际变化，不执行更新')
            return
          }
          
          // 获取旧答案（如果存在）
          const oldAnswer = this.answers[this.currentQuestion.id]
          
          // 先将新答案保存到answers对象中
          this.$set(this.answers, this.currentQuestion.id, value)
          
          // 如果是首次回答，直接加分
          if (!oldAnswer) {
            console.log('首次回答，直接添加分数')
            this.addQuestionScores(this.currentQuestion, value)
          } 
          // 如果是更改答案，先减去旧分数，再加上新分数
          else {
            console.log('更改答案，先减旧分数再加新分数')
            this.resetQuestionScores(this.currentQuestion)
            this.addQuestionScores(this.currentQuestion, value)
          }
          
          this.saveProgress() // 保存进度
        }
      }
    },
    progressPercentage() {
      // 确保返回一个有效的数字（0-100之间）
      const percentage = Math.round((this.currentIndex + 1) / this.totalQuestions * 100)
      return Math.max(0, Math.min(100, percentage))
    },
    isLastQuestion() {
      return this.currentIndex === this.totalQuestions - 1
    },
    // 获取当前用户ID
    currentUserId() {
      const user = JSON.parse(localStorage.getItem('user') || '{}')
      return user.userId
    }
  },
  async created() {
    // 首先检查用户是否已经完成测试，如果已完成则跳转回首页
    try {
      this.loading = true
      const user = JSON.parse(localStorage.getItem('user') || '{}')
      
      // 只有在有用户信息的情况下才检查
      if (user && user.userId) {
        const res = await testApi.getByUserId(user.userId)
        if (res.code === 200 && res.data && res.data.length > 0) {
          // 用户已经有测试结果，跳转到首页
          this.$message.info('您已经完成了测试，如需重新测试请从首页开始')
          this.$router.push('/home')
          return
        }
      }
      
      // 如果没有测试结果，或者获取失败，继续加载测试题目
      await this.loadQuestions()
    } catch (error) {
      console.error('检查测试状态失败：', error)
      // 如果出错，仍尝试加载测试题目
      await this.loadQuestions()
    } finally {
      this.loading = false
    }
  },
  beforeDestroy() {
    // 组件销毁前保存进度
    this.saveProgress(true)
    // 清除定时器
    if (this.saveTimer) {
      clearTimeout(this.saveTimer)
    }
  },
  methods: {
    async loadQuestions() {
      if (!this.dimensions || !Array.isArray(this.dimensions)) {
        throw new Error('维度配置错误')
      }

      try {
        this.loading = true
        console.log('开始加载题目...')
        
        // 获取所有题目
        const response = await testApi.getAllQuestions()
        console.log('获取到的原始数据：', response)
        
        if (!response || !response.data) {
          console.error('服务器返回数据：', response)
          throw new Error('服务器返回数据格式错误')
        }
        
        // 兼容处理 list 和 records 两种返回格式
        const allQuestions = response.data || []
        if (!Array.isArray(allQuestions)) {
          console.error('题目数据格式错误：', response.data)
          throw new Error('题目数据格式错误')
        }
        
        console.log('所有题目：', allQuestions)
        
        // 按维度分类并随机选择题目
        this.questions = []
        const questionsPerDimension = 10 // 每个维度固定10道题，总计40道题
        
        for (let i = 0; i < this.dimensions.length; i++) {
          const dimension = this.dimensions[i]
          const dimensionQuestions = allQuestions.filter(q => q.dimension === dimension)
          console.log(`${dimension} 维度的题目:`, dimensionQuestions)
          
          if (dimensionQuestions.length > 0) {
            // 随机打乱该维度的题目
            const shuffled = dimensionQuestions.sort(() => Math.random() - 0.5)
            // 每个维度选择固定数量的题目
            const selected = shuffled.slice(0, questionsPerDimension)
            
            const formattedQuestions = selected.map(q => {
              // 确保所有必要的字段都存在
              if (!q.content || !q.optionA || !q.optionB) {
                console.warn('题目数据不完整：', q)
                return null
              }
              
              // 打印原始题目分数数据
              console.log('原始题目分数数据（未处理）：', {
                id: q.id,
                aescore: q.aescore, 
                aiscore: q.aiscore,
                asscore: q.asscore, 
                anscore: q.anscore,
                atscore: q.atscore, 
                afscore: q.afscore,
                ajscore: q.ajscore, 
                apscore: q.apscore,
                bescore: q.bescore, 
                biscore: q.biscore,
                bsscore: q.bsscore, 
                bnscore: q.bnscore,
                btscore: q.btscore, 
                bfscore: q.bfscore,
                bjscore: q.bjscore, 
                bpscore: q.bpscore
              });
              
              // 打印题目分数数据的类型
              console.log('题目分数数据类型：', {
                id: q.id,
                // 检查小写字段名
                aescore: typeof q.aescore, aiscore: typeof q.aiscore,
                asscore: typeof q.asscore, anscore: typeof q.anscore,
                atscore: typeof q.atscore, afscore: typeof q.afscore,
                ajscore: typeof q.ajscore, apscore: typeof q.apscore,
                bescore: typeof q.bescore, biscore: typeof q.biscore,
                bsscore: typeof q.bsscore, bnscore: typeof q.bnscore,
                btscore: typeof q.btscore, bfscore: typeof q.bfscore,
                bjscore: typeof q.bjscore, bpscore: typeof q.bpscore
              });
              
              // 转换分数字段为数字类型
              const convertToNumber = (value) => {
                if (value === null || value === undefined) return 0;
                return typeof value === 'string' ? Number(value) : (typeof value === 'number' ? value : 0);
              };
              
              // 使用小写字段名处理分数
              // 为了代码兼容性，同时设置驼峰命名和小写命名的字段
              q.aEScore = convertToNumber(q.aescore);
              q.aIScore = convertToNumber(q.aiscore);
              q.aSScore = convertToNumber(q.asscore);
              q.aNScore = convertToNumber(q.anscore);
              q.aTScore = convertToNumber(q.atscore);
              q.aFScore = convertToNumber(q.afscore);
              q.aJScore = convertToNumber(q.ajscore);
              q.aPScore = convertToNumber(q.apscore);
              q.bEScore = convertToNumber(q.bescore);
              q.bIScore = convertToNumber(q.biscore);
              q.bSScore = convertToNumber(q.bsscore);
              q.bNScore = convertToNumber(q.bnscore);
              q.bTScore = convertToNumber(q.btscore);
              q.bFScore = convertToNumber(q.bfscore);
              q.bJScore = convertToNumber(q.bjscore);
              q.bPScore = convertToNumber(q.bpscore);
              
              // 转换后打印验证
              console.log('转换后的分数：', {
                id: q.id,
                // 验证设置的驼峰命名字段
                aEScore: q.aEScore, aIScore: q.aIScore,
                aSScore: q.aSScore, aNScore: q.aNScore,
                aTScore: q.aTScore, aFScore: q.aFScore,
                aJScore: q.aJScore, aPScore: q.aPScore,
                bEScore: q.bEScore, bIScore: q.bIScore,
                bSScore: q.bSScore, bNScore: q.bNScore,
                bTScore: q.bTScore, bFScore: q.bFScore,
                bJScore: q.bJScore, bPScore: q.bPScore
              });
              
              return {
                id: q.id,
                content: q.content,
                dimension: q.dimension,
                options: [
                  { 
                    label: q.optionA, 
                    value: 'A',
                    scores: {
                      E: q.aEScore,
                      I: q.aIScore,
                      S: q.aSScore,
                      N: q.aNScore,
                      T: q.aTScore,
                      F: q.aFScore,
                      J: q.aJScore,
                      P: q.aPScore
                    }
                  },
                  { 
                    label: q.optionB, 
                    value: 'B',
                    scores: {
                      E: q.bEScore,
                      I: q.bIScore,
                      S: q.bSScore,
                      N: q.bNScore,
                      T: q.bTScore,
                      F: q.bFScore,
                      J: q.bJScore,
                      P: q.bPScore
                    }
                  }
                ]
              }
            }).filter(q => q !== null) // 过滤掉不完整的题目
            
            this.questions.push(...formattedQuestions)
          }
        }
        
        // 检查题目数量
        if (this.questions.length < 5) {
          throw new Error('题目数量不足，请联系管理员')
        }
        
        // 按题目ID排序
        this.questions.sort((a, b) => a.id - b.id)
        
        console.log('最终选择的题目：', this.questions)
        
        // 加载保存的进度（如果存在）
        // 在题目加载完成后，检查是否有未完成的测试
        const userId = this.currentUserId
        if (userId) {
          const savedProgress = localStorage.getItem(`mbti_progress_${userId}`)
          if (savedProgress) {
            try {
              const progress = JSON.parse(savedProgress)
              const timestamp = progress.timestamp
              const now = new Date().getTime()
              const hoursPassed = (now - timestamp) / (1000 * 60 * 60)
              
              // 如果保存的进度超过24小时，则不恢复
              if (hoursPassed > 24) {
                localStorage.removeItem(`mbti_progress_${userId}`)
              } else {
                // 显示确认对话框
                this.$confirm('检测到您有未完成的测试，是否继续？', '提示', {
                  confirmButtonText: '继续测试',
                  cancelButtonText: '重新开始',
                  type: 'info'
                }).then(() => {
                  // 恢复进度
                  console.log('继续未完成的测试，恢复进度')
                  this.currentIndex = progress.currentIndex || 0
                  this.answers = progress.answers || {}
                  this.scores = progress.scores || {
                    E: 0, I: 0, S: 0, N: 0, T: 0, F: 0, J: 0, P: 0
                  }
                }).catch(() => {
                  // 重新开始，清除保存的进度
                  console.log('重新开始测试，清除保存的进度')
                  localStorage.removeItem(`mbti_progress_${userId}`)
                  // 重置状态
                  this.currentIndex = 0
                  this.answers = {}
                  this.scores = { E: 0, I: 0, S: 0, N: 0, T: 0, F: 0, J: 0, P: 0 }
                })
              }
            } catch (error) {
              console.error('解析保存的进度失败：', error)
              localStorage.removeItem(`mbti_progress_${userId}`)
            }
          }
        }
        
      } catch (error) {
        console.error('加载题目失败：', error)
        this.$message.error(error.message || '加载题目失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    updateScores(question, answer) {
      console.log('updateScores方法已废弃，使用addQuestionScores和resetQuestionScores代替')
      // 该方法不做任何操作
    },
    resetQuestionScores(question) {
      const oldAnswer = this.answers[question.id]
      if (!oldAnswer || !question) {
        console.log('无需重置分数：没有之前的答案或问题无效')
        return
      }
      
      // 获取之前选择的选项的分数
      const oldOption = oldAnswer === 'A' ? question.options[0] : question.options[1]
      if (!oldOption || !oldOption.scores) {
        console.error('之前的选项或分数数据无效：', oldOption)
        return
      }
      
      console.log('重置之前的分数：', {
        oldAnswer,
        oldScores: oldOption.scores
      })
      
      // 记录重置前的分数
      console.log('重置前的总分：', JSON.stringify(this.scores))
      
      // 直接使用原始分数值
      const scoreE = oldOption.scores.E || 0
      const scoreI = oldOption.scores.I || 0
      const scoreS = oldOption.scores.S || 0
      const scoreN = oldOption.scores.N || 0
      const scoreT = oldOption.scores.T || 0
      const scoreF = oldOption.scores.F || 0
      const scoreJ = oldOption.scores.J || 0
      const scoreP = oldOption.scores.P || 0
      
      // 打印原始分数值的类型
      console.log('重置分数值的类型：', {
        E: typeof scoreE, I: typeof scoreI,
        S: typeof scoreS, N: typeof scoreN,
        T: typeof scoreT, F: typeof scoreF,
        J: typeof scoreJ, P: typeof scoreP
      });
      
      // 确保所有分数值都是数字类型
      const numE = Number(scoreE);
      const numI = Number(scoreI);
      const numS = Number(scoreS);
      const numN = Number(scoreN);
      const numT = Number(scoreT);
      const numF = Number(scoreF);
      const numJ = Number(scoreJ);
      const numP = Number(scoreP);
      
      console.log('将要减去的分数：', {
        E: numE, I: numI, 
        S: numS, N: numN, 
        T: numT, F: numF, 
        J: numJ, P: numP
      });
      
      // 确保当前scores是数字类型
      this.scores.E = Number(this.scores.E || 0);
      this.scores.I = Number(this.scores.I || 0);
      this.scores.S = Number(this.scores.S || 0);
      this.scores.N = Number(this.scores.N || 0);
      this.scores.T = Number(this.scores.T || 0);
      this.scores.F = Number(this.scores.F || 0);
      this.scores.J = Number(this.scores.J || 0);
      this.scores.P = Number(this.scores.P || 0);
      
      // 直接从总分中减去所有分数
      this.scores.E -= numE;
      this.scores.I -= numI;
      this.scores.S -= numS;
      this.scores.N -= numN;
      this.scores.T -= numT;
      this.scores.F -= numF;
      this.scores.J -= numJ;
      this.scores.P -= numP;
      
      console.log('重置后的总分：', {
        scores: this.scores,
        E: this.scores.E,
        I: this.scores.I,
        S: this.scores.S,
        N: this.scores.N,
        T: this.scores.T,
        F: this.scores.F,
        J: this.scores.J,
        P: this.scores.P
      })
    },
    // 保存进度
    saveProgress(immediate = false) {
      if (this.saveTimer) {
        clearTimeout(this.saveTimer)
      }
      
      const save = () => {
        const progress = {
          currentIndex: this.currentIndex,
          answers: this.answers,
          scores: this.scores,
          questions: this.questions,
          timestamp: new Date().getTime()
        }
        localStorage.setItem(`mbti_progress_${this.currentUserId}`, JSON.stringify(progress))
      }
      
      if (immediate) {
        save()
      } else {
        // 使用防抖，避免频繁保存
        this.saveTimer = setTimeout(save, 500)
      }
    },
    // 加载进度
    loadProgress() {
      const savedProgress = localStorage.getItem(`mbti_progress_${this.currentUserId}`)
      if (!savedProgress) return
      
      try {
        const progress = JSON.parse(savedProgress)
        const timestamp = progress.timestamp
        const now = new Date().getTime()
        const hoursPassed = (now - timestamp) / (1000 * 60 * 60)
        
        // 如果保存的进度超过24小时，则不恢复
        if (hoursPassed > 24) {
          localStorage.removeItem(`mbti_progress_${this.currentUserId}`)
          return
        }
        
        // 确认是否要恢复进度
        this.$confirm('检测到您有未完成的测试，是否继续？', '提示', {
          confirmButtonText: '继续测试',
          cancelButtonText: '重新开始',
          type: 'info'
        }).then(() => {
          // 恢复进度
          this.currentIndex = progress.currentIndex
          this.answers = progress.answers
          this.scores = progress.scores
          // 不需要恢复questions，因为我们已经重新加载了
        }).catch(() => {
          // 重新开始，清除保存的进度
          localStorage.removeItem(`mbti_progress_${this.currentUserId}`)
        })
      } catch (error) {
        console.error('恢复进度失败：', error)
        localStorage.removeItem(`mbti_progress_${this.currentUserId}`)
      }
    },
    handleAnswer(value) {
      if (this.isLastQuestion) {
        this.submitTest()
      }
    },
    prevQuestion() {
      if (this.currentIndex > 0) {
        this.currentIndex--
        this.saveProgress(true) // 立即保存进度
      }
    },
    nextQuestion() {
      if (this.currentIndex < this.totalQuestions - 1) {
        this.currentIndex++
        this.saveProgress(true) // 立即保存进度
      } else {
        this.submitTest()
      }
    },
    async submitTest() {
      try {
        // 检查是否所有题目都已回答
        const answeredQuestions = Object.keys(this.answers).length
        if (answeredQuestions < this.questions.length) {
          this.$message.warning(`还有 ${this.questions.length - answeredQuestions} 题未回答`)
          return
        }

        this.loading = true
        const user = JSON.parse(localStorage.getItem('user') || '{}')
        
        // 打印原始分数
        console.log('提交前的原始分数：', {
          scores: this.scores,
          E: this.scores.E,
          I: this.scores.I,
          S: this.scores.S,
          N: this.scores.N,
          T: this.scores.T,
          F: this.scores.F,
          J: this.scores.J,
          P: this.scores.P
        });
        
        // 打印所有回答的题目和选择的答案，以及对应的分数
        console.log('所有答案详情：');
        Object.keys(this.answers).forEach(questionId => {
          const question = this.questions.find(q => q.id == questionId);
          if (question) {
            const answer = this.answers[questionId];
            const option = answer === 'A' ? question.options[0] : question.options[1];
            console.log(`题目ID: ${questionId}, 内容: ${question.content.substring(0, 30)}..., 答案: ${answer}, 选项分数:`, option.scores);
          }
        });
        
        // 确保分数都是数字，如果是null或undefined则设为0
        const safeScores = {
          E: this.scores.E || 0,
          I: this.scores.I || 0,
          S: this.scores.S || 0,
          N: this.scores.N || 0,
          T: this.scores.T || 0,
          F: this.scores.F || 0,
          J: this.scores.J || 0,
          P: this.scores.P || 0
        };
        
        // 计算每个维度的题目数量（根据已回答的题目）
        const countsByDimension = {};
        Object.keys(this.answers).forEach(questionId => {
          const question = this.questions.find(q => q.id == questionId);
          if (question) {
            const dimension = question.dimension;
            countsByDimension[dimension] = (countsByDimension[dimension] || 0) + 1;
          }
        });
        
        // 打印出每个维度的题目数量
        console.log('每个维度的题目数量：', countsByDimension);

        // 根据分数计算MBTI类型结果
        // 每个维度的得分占比，分别是E/I, S/N, T/F, J/P
        const scorePairs = [
          {dimension: 'E-I', scores: [safeScores.E, safeScores.I]},
          {dimension: 'S-N', scores: [safeScores.S, safeScores.N]},
          {dimension: 'T-F', scores: [safeScores.T, safeScores.F]},
          {dimension: 'J-P', scores: [safeScores.J, safeScores.P]}
        ];
        
        // 计算百分比（用于展示）
        const scoreData = scorePairs.map(pair => {
          const total = pair.scores[0] + pair.scores[1];
          let scores = [0, 0];
          if (total > 0) {
            scores = [
              Math.round(pair.scores[0] / total * 100),
              Math.round(pair.scores[1] / total * 100)
            ];
          }
          return {dimension: pair.dimension, scores};
        });
        
        // 打印最终的百分比分数
        console.log('最终分数百分比：', scoreData);
        
        const mbtiType = this.calculateMbtiType({
          eScore: safeScores.E, 
          iScore: safeScores.I, 
          sScore: safeScores.S, 
          nScore: safeScores.N, 
          tScore: safeScores.T, 
          fScore: safeScores.F, 
          jScore: safeScores.J, 
          pScore: safeScores.P
        });
        
        // 获取MBTI类型名称
        const typeName = this.getMbtiTypeName(mbtiType);
        
        // 构建提交数据，使用原始分值而不是百分比
        const result = {
          userId: user.userId,
          testTime: new Date().toISOString(), // 添加测试完成时间
          mbtiType: mbtiType,
          typeName: typeName,
          eScore: safeScores.E,
          iScore: safeScores.I,
          sScore: safeScores.S,
          nScore: safeScores.N,
          tScore: safeScores.T,
          fScore: safeScores.F,
          jScore: safeScores.J,
          pScore: safeScores.P
        };
        
        // 打印最终提交的数据
        console.log('提交的测试结果（原始格式）:', result);
        console.log('提交的测试结果（JSON字符串）:', JSON.stringify(result));
        
        const res = await testApi.submitResult(result)
        if (res.code === 200) {
          // 保存测试结果到本地，并标记测试已完成
          this.testSubmitted = true
          localStorage.setItem(`test_submitted_${user.userId}`, 'true')
          
          // 清除之前保存的未完成测试进度
          localStorage.removeItem(`mbti_progress_${this.currentUserId}`)
          
          console.log('测试结果已保存，ID:', res.data.id)
          
          // 获取MBTI类型描述
          const typeDescription = await mbtiTypeApi.get(mbtiType)
          
          // 展示测试结果对话框
          this.$confirm(`
            <div class="test-result">
              <div class="result-header">
                <div class="completion-icon">
                  <i class="el-icon-check"></i>
                </div>
              <h2>测试完成！</h2>
              </div>
              
              <div class="mbti-type">
                <div class="type-badge">
                  <span class="type-code">${mbtiType}</span>
                  <span class="type-name">${typeName}</span>
              </div>
              </div>

              <div class="dimension-scores">
                <h3>性格维度分析</h3>
                <div class="score-grid">
                  ${scoreData.map(d => {
                    const [dim1, dim2] = d.dimension.split('-');
                    const [score1, score2] = d.scores;
                    return `
                      <div class="score-item">
                        <div class="dimension-labels">
                          <span class="dim-label ${score1 >= score2 ? 'active' : ''}">${dim1}</span>
                          <span class="dim-label ${score2 >= score1 ? 'active' : ''}">${dim2}</span>
                        </div>
                        <div class="score-bar-container">
                    <div class="score-bar">
                            <div class="score-fill" style="width: ${score1}%; background-color: ${score1 >= score2 ? '#409EFF' : '#909399'}"></div>
                            <div class="score-fill" style="width: ${score2}%; background-color: ${score2 >= score1 ? '#409EFF' : '#909399'}"></div>
                    </div>
                  </div>
                        <div class="score-values">
                          <span>${score1}%</span>
                          <span>${score2}%</span>
              </div>
              </div>
                    `;
                  }).join('')}
                </div>
              </div>

              <div class="result-summary">
                <div class="summary-icon">
                  <i class="el-icon-info"></i>
                </div>
                <p class="summary-text">
                  点击"查看详细结果"了解更多关于您的性格类型特征、职业发展方向和个人成长建议。
                </p>
              </div>
            </div>
          `, '测试结果', {
            confirmButtonText: '查看详细结果',
            cancelButtonText: '返回首页',
            dangerouslyUseHTMLString: true,
            customClass: 'test-result-dialog'
          }).then(() => {
            // 显示详细结果弹窗
            this.$alert(`
              <div class="mbti-detail-result">
                <div class="detail-header">
                  <div class="type-info">
                    <div class="type-title">
                      <span class="type-code">${mbtiType}</span>
                      <span class="type-name">${typeName}</span>
                    </div>
                  </div>
                </div>

                <div class="detail-content">
                      <div class="tab-content personality">
                        <h4>性格描述</h4>
                        <div class="content-box description">
                          ${typeDescription.data.description || '暂无描述'}
                        </div>
                          </div>
                </div>
              </div>
            `, '详细结果', {
              confirmButtonText: '返回首页',
              dangerouslyUseHTMLString: true,
              customClass: 'mbti-detail-dialog',
              callback: () => {
                this.$router.push('/home');
              }
            });
          }).catch(() => {
            // 返回首页
            this.$router.push('/home')
          })
        } else {
          this.$message.error(res.message || '提交失败')
        }
      } catch (error) {
        console.error('提交测试失败：', error)
        this.$message.error('提交失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    
    // 处理测试结果数据的方法
    processTestResult(data) {
      if (!data) return null;
      
      // 创建结果对象
      const result = { ...data };
      
      // 分数字段映射（小写 -> 驼峰）
      const scoreFields = {
        'escore': 'eScore',
        'iscore': 'iScore',
        'sscore': 'sScore',
        'nscore': 'nScore',
        'tscore': 'tScore',
        'fscore': 'fScore',
        'jscore': 'jScore',
        'pscore': 'pScore'
      };
      
      // 将小写分数字段转换为驼峰命名字段
      for (const key in scoreFields) {
        if (data[key] !== undefined && data[key] !== null) {
          const camelCaseKey = scoreFields[key];
          const value = Number(data[key]);
          // 允许分数为0
          result[camelCaseKey] = Math.max(0, value);
        }
      }
      
      // 确保所有分数字段都是数字类型
      for (const key in result) {
        if (key.toLowerCase().includes('score')) {
          if (typeof result[key] === 'string') {
            result[key] = Number(result[key]);
          }
        }
      }
      
      // 确保mbtiType字段存在（驼峰命名）
      if (!result.mbtiType && result.mbtitype) {
        result.mbtiType = result.mbtitype;
      }
      
      return result;
    },
    // 获取MBTI类型名称
    getMbtiTypeName(mbtiType) {
      const typeNames = {
        'ISTJ': '检查者',
        'ISFJ': '保护者',
        'INFJ': '咨询师',
        'INTJ': '建筑师',
        'ISTP': '鉴赏家',
        'ISFP': '探险家',
        'INFP': '调停者',
        'INTP': '逻辑学家',
        'ESTP': '企业家',
        'ESFP': '表演者',
        'ENFP': '竞选者',
        'ENTP': '辩论家',
        'ESTJ': '总经理',
        'ESFJ': '执政官',
        'ENFJ': '主人公',
        'ENTJ': '指挥官'
      };
      
      return typeNames[mbtiType] || '未知类型';
    },
    // 计算MBTI类型
    calculateMbtiType(result) {
      let mbtiType = '';
      
      // E-I 维度
      mbtiType += result.eScore > result.iScore ? 'E' : 'I';
      
      // S-N 维度
      mbtiType += result.sScore > result.nScore ? 'S' : 'N';
      
      // T-F 维度
      mbtiType += result.tScore > result.fScore ? 'T' : 'F';
      
      // J-P 维度
      mbtiType += result.jScore > result.pScore ? 'J' : 'P';
      
      return mbtiType;
    },
    // 新增方法：仅添加分数，不做任何重置
    addQuestionScores(question, answer) {
      if (!question || !answer) {
        console.warn('addQuestionScores: 无效的问题或答案', { question, answer })
        return
      }
      
      console.log('======= addQuestionScores 开始执行 =======')
      
      // 获取选项的分数
      const option = answer === 'A' ? question.options[0] : question.options[1]
      if (!option || !option.scores) {
        console.error('选项或分数数据无效：', option)
        return
      }
      
      // 增加调试输出
      console.log('选项的完整数据：', option)
      console.log('scores对象是否存在：', !!option.scores)
      console.log('scores对象的内容：', option.scores)
      
      // 记录更新前的分数
      console.log('更新前的总分：', JSON.stringify(this.scores))
      
      // 直接使用原始分数值
      const scoreE = option.scores.E || 0
      const scoreI = option.scores.I || 0
      const scoreS = option.scores.S || 0
      const scoreN = option.scores.N || 0
      const scoreT = option.scores.T || 0
      const scoreF = option.scores.F || 0
      const scoreJ = option.scores.J || 0
      const scoreP = option.scores.P || 0
      
      // 打印原始分数值的类型
      console.log('分数值的类型：', {
        E: typeof scoreE, I: typeof scoreI,
        S: typeof scoreS, N: typeof scoreN,
        T: typeof scoreT, F: typeof scoreF,
        J: typeof scoreJ, P: typeof scoreP
      });
      
      // 确保所有分数值都是数字类型
      const numE = Number(scoreE);
      const numI = Number(scoreI);
      const numS = Number(scoreS);
      const numN = Number(scoreN);
      const numT = Number(scoreT);
      const numF = Number(scoreF);
      const numJ = Number(scoreJ);
      const numP = Number(scoreP);
      
      console.log('将要添加的分数：', {
        E: numE, I: numI, 
        S: numS, N: numN, 
        T: numT, F: numF, 
        J: numJ, P: numP
      });
      
      // 确保当前scores是数字类型
      this.scores.E = Number(this.scores.E || 0);
      this.scores.I = Number(this.scores.I || 0);
      this.scores.S = Number(this.scores.S || 0);
      this.scores.N = Number(this.scores.N || 0);
      this.scores.T = Number(this.scores.T || 0);
      this.scores.F = Number(this.scores.F || 0);
      this.scores.J = Number(this.scores.J || 0);
      this.scores.P = Number(this.scores.P || 0);
      
      // 添加明显的日志标记，确认代码执行到了这里
      console.log('===== 即将执行分数加法 =====');
      
      // 加上新分数
      this.scores.E += numE;
      this.scores.I += numI;
      this.scores.S += numS;
      this.scores.N += numN;
      this.scores.T += numT;
      this.scores.F += numF;
      this.scores.J += numJ;
      this.scores.P += numP;
      
      // 添加明显的日志标记，确认分数加法已执行完毕
      console.log('===== 分数加法已执行完毕 =====');
      
      console.log('更新后的总分：', {
        scores: this.scores,
        E: this.scores.E,
        I: this.scores.I,
        S: this.scores.S,
        N: this.scores.N,
        T: this.scores.T,
        F: this.scores.F,
        J: this.scores.J,
        P: this.scores.P
      })
    }
  }
}
</script>

<style scoped>
.mbti-test {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.test-container {
  background: #fff;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

/* 测试结果对话框样式 */
:deep(.test-result-dialog) {
  .el-message-box {
    max-width: 600px;
    border-radius: 8px;
  
    .el-message-box__header {
    padding: 20px;
      border-bottom: 1px solid #EBEEF5;
      
      .el-message-box__title {
        font-size: 20px;
        font-weight: bold;
        color: #303133;
      }
    }
    
    .el-message-box__content {
      padding: 30px;
    }
  }
  
  .test-result {
    .result-header {
      text-align: center;
      margin-bottom: 30px;
      
      .completion-icon {
        margin-bottom: 15px;
        
        i {
          font-size: 48px;
          color: #67C23A;
        }
      }
      
      h2 {
        font-size: 24px;
      color: #303133;
        margin: 0;
      }
    }
    
    .mbti-type {
      text-align: center;
      margin-bottom: 30px;
      
      .type-badge {
        display: inline-flex;
        align-items: center;
        background: #F2F6FC;
        padding: 10px 20px;
        border-radius: 20px;
        
        .type-code {
        font-size: 24px;
          font-weight: bold;
        color: #409EFF;
          margin-right: 10px;
      }
      
        .type-name {
          font-size: 18px;
        color: #606266;
        }
      }
    }
    
    .dimension-scores {
      margin-bottom: 30px;
      
      h3 {
        font-size: 18px;
        color: #303133;
        margin-bottom: 20px;
        text-align: center;
      }
      
      .score-grid {
        .score-item {
          margin-bottom: 20px;
          
          .dimension-labels {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
            
            .dim-label {
              font-size: 14px;
              color: #909399;
              
              &.active {
                color: #409EFF;
          font-weight: bold;
              }
            }
        }
          
          .score-bar-container {
            margin: 5px 0;
        
        .score-bar {
              height: 8px;
              background: #F2F6FC;
              border-radius: 4px;
          display: flex;
          overflow: hidden;
          
              .score-fill {
                height: 100%;
            transition: width 0.3s ease;
              }
            }
          }
          
          .score-values {
            display: flex;
            justify-content: space-between;
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
    
    .result-summary {
      text-align: center;
      background: #F2F6FC;
      padding: 20px;
      border-radius: 8px;
      
      .summary-icon {
        margin-bottom: 10px;
        
        i {
          font-size: 24px;
          color: #909399;
        }
      }
      
      .summary-text {
        color: #606266;
        margin: 0;
        line-height: 1.5;
      }
    }
  }
}

/* 详细结果弹窗样式 */
:deep(.mbti-detail-dialog) {
  .el-message-box {
    max-width: 600px;
    width: 90%;
    border-radius: 8px;
    
    .el-message-box__header {
      padding: 20px;
      border-bottom: 1px solid #EBEEF5;
      
      .el-message-box__title {
        font-size: 20px;
        font-weight: bold;
        color: #303133;
      }
    }
    
    .el-message-box__content {
      padding: 0;
      max-height: 70vh;
      overflow-y: auto;
    }
  }
  
  .mbti-detail-result {
    .detail-header {
      text-align: center;
      margin: 20px 0;
      
      .type-title {
        display: inline-flex;
        align-items: center;
        background: #F2F6FC;
        padding: 12px 25px;
        border-radius: 25px;
        box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
        
        .type-code {
          font-size: 28px;
          font-weight: bold;
        color: #409EFF;
          margin-right: 15px;
      }
      
        .type-name {
          font-size: 22px;
        color: #606266;
        }
      }
    }
    
    .detail-content {
          padding: 25px;
          
          .tab-content {
            h4 {
              font-size: 16px;
              color: #303133;
              margin: 0 0 15px;
              padding-left: 12px;
              border-left: 3px solid #409EFF;
              line-height: 1.4;
              font-weight: 500;
            }
            
            .content-box {
              background: #F8F9FB;
              padding: 20px;
              border-radius: 8px;
              color: #606266;
              line-height: 1.8;
              margin-bottom: 25px;
              transition: all 0.3s ease;
              
              &:hover {
                background: #F2F6FC;
                transform: translateY(-2px);
                box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
              }
            }
      }
    }
  }
}

.progress-bar {
  margin-bottom: 30px;
}

.question-container {
  margin-bottom: 30px;
}

.question-title {
  font-size: 18px;
  color: #303133;
  margin-bottom: 20px;
  line-height: 1.6;
}

.options {
  margin-top: 20px;
}

.option-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.option-item {
  margin: 0;
  padding: 15px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  transition: all 0.3s;
}

.option-item:hover {
  background-color: #F5F7FA;
}

.navigation-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
}

.no-questions {
  text-align: center;
  padding: 40px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}
</style>